package com.cci.kangdao.fieldService.service.impl;

import com.cci.kangdao.aop.UserThreadLocal;
import com.cci.kangdao.dao.model.UserT;
import com.cci.kangdao.dto.PagedRequest;
import com.cci.kangdao.dto.PagedResponse;
import com.cci.kangdao.fieldService.aop.model.ChannelThreadLocal;
import com.cci.kangdao.fieldService.dao.FieldServiceAgreementDao;
import com.cci.kangdao.fieldService.dao.FieldServiceEngineerDao;
import com.cci.kangdao.fieldService.dao.FieldServiceInvestigationDao;
import com.cci.kangdao.fieldService.dao.FieldServiceInvestigationReportDao;
import com.cci.kangdao.fieldService.dao.FieldServiceItemDao;
import com.cci.kangdao.fieldService.dao.FieldServiceReportResultDao;
import com.cci.kangdao.fieldService.dao.FieldServiceTemplateDao;
import com.cci.kangdao.fieldService.dao.FieldServiceTemplateParamDao;
import com.cci.kangdao.fieldService.dao.FieldServiceTemplatePickParamDao;
import com.cci.kangdao.fieldService.dao.FieldServiceTemplateSectionDao;
import com.cci.kangdao.fieldService.dao.FieldServiceTemplateStandardDao;
import com.cci.kangdao.fieldService.dao.FieldServiceUpgradeDao;
import com.cci.kangdao.fieldService.dao.FieldServiceWorkOrderDao;
import com.cci.kangdao.fieldService.dto.request.CreateInvestigationRequest;
import com.cci.kangdao.fieldService.dto.request.CreateWorkOrderRequest;
import com.cci.kangdao.fieldService.dto.request.DeleteInvestigationRequest;
import com.cci.kangdao.fieldService.dto.request.DeleteReportRequest;
import com.cci.kangdao.fieldService.dto.request.EditTemplateSectionRequest;
import com.cci.kangdao.fieldService.dto.request.ReportResultRequest;
import com.cci.kangdao.fieldService.dto.request.SelectTemplateRequest;
import com.cci.kangdao.fieldService.dto.request.StartItemServiceRequest;
import com.cci.kangdao.fieldService.dto.request.UpdateReportRequest;
import com.cci.kangdao.fieldService.dto.request.WorkOrderCompletionRequest;
import com.cci.kangdao.fieldService.dto.request.WorkOrderUpgradeRequest;
import com.cci.kangdao.fieldService.dto.response.CreateInvestigationResponse;
import com.cci.kangdao.fieldService.dto.response.GetAgreementResponse;
import com.cci.kangdao.fieldService.dto.response.GetInvestigationListResponse;
import com.cci.kangdao.fieldService.dto.response.GetInvestigationResponse;
import com.cci.kangdao.fieldService.dto.response.GetItemResponse;
import com.cci.kangdao.fieldService.dto.response.GetOrderDetailResponse;
import com.cci.kangdao.fieldService.dto.response.GetOrderResponse;
import com.cci.kangdao.fieldService.dto.response.GetReportListResponse;
import com.cci.kangdao.fieldService.dto.response.GetReportResponse;
import com.cci.kangdao.fieldService.dto.response.GetTemplateListResponse;
import com.cci.kangdao.fieldService.dto.response.GetTemplateParamResponse;
import com.cci.kangdao.fieldService.dto.response.GetTemplateResponse;
import com.cci.kangdao.fieldService.dto.response.GetTemplateSectionResponse;
import com.cci.kangdao.fieldService.dto.response.GetUpgradeListResponse;
import com.cci.kangdao.fieldService.dto.response.GetUpgradeResponse;
import com.cci.kangdao.fieldService.dto.response.GetWorkOrderResponse;
import com.cci.kangdao.fieldService.dto.response.StartItemServiceResponse;
import com.cci.kangdao.fieldService.model.FieldServiceAgreement;
import com.cci.kangdao.fieldService.model.FieldServiceEngineer;
import com.cci.kangdao.fieldService.model.FieldServiceInvestigation;
import com.cci.kangdao.fieldService.model.FieldServiceInvestigationReport;
import com.cci.kangdao.fieldService.model.FieldServiceItem;
import com.cci.kangdao.fieldService.model.FieldServiceReportResult;
import com.cci.kangdao.fieldService.model.FieldServiceTemplate;
import com.cci.kangdao.fieldService.model.FieldServiceTemplateParam;
import com.cci.kangdao.fieldService.model.FieldServiceTemplatePickParam;
import com.cci.kangdao.fieldService.model.FieldServiceTemplateSection;
import com.cci.kangdao.fieldService.model.FieldServiceTemplateStandard;
import com.cci.kangdao.fieldService.model.FieldServiceUpgrade;
import com.cci.kangdao.fieldService.model.FieldServiceWorkOrder;
import com.cci.kangdao.fieldService.model.ReportResult;
import com.cci.kangdao.fieldService.model.type.BooleanType;
import com.cci.kangdao.fieldService.model.type.FieldServiceAgreementCategory;
import com.cci.kangdao.fieldService.model.type.FieldServiceDictionaryType;
import com.cci.kangdao.fieldService.model.type.FieldServiceItemStatus;
import com.cci.kangdao.fieldService.model.type.FieldServiceItemType;
import com.cci.kangdao.fieldService.model.type.FieldServiceTemplateType;
import com.cci.kangdao.fieldService.model.type.FieldServiceUpgradeStatus;
import com.cci.kangdao.fieldService.model.type.FieldServiceUpgradeType;
import com.cci.kangdao.fieldService.model.type.FieldServiceWorkOrderStatus;
import com.cci.kangdao.fieldService.model.type.SyncInterface;
import com.cci.kangdao.fieldService.model.type.WorkOrderFlowProcessorType;
import com.cci.kangdao.fieldService.service.FieldBaseService;
import com.cci.kangdao.fieldService.service.FieldServiceReportService;
import com.cci.kangdao.fieldService.service.FieldServiceService;
import com.cci.kangdao.fieldService.service.FieldServiceWorkOrderFlowService;
import com.cci.kangdao.fieldService.service.SyncProcessor;
import com.cci.kangdao.service.DictionariesTService;
import com.cci.kangdao.utilTool.BeanUtils;
import com.cci.kangdao.utilTool.CollectionUtils;
import com.cci.kangdao.utilTool.JsonUtils;
import com.cci.kangdao.utilTool.LocalTimeUtil;
import com.cci.kangdao.utilTool.NumberUtils;
import com.cci.kangdao.utilTool.ParameterTool;
import com.cci.kangdao.utilTool.RequestContextHolder;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author William Du
 * @date 2020/1/2
 */
@Service
public class FieldServiceServiceImpl extends FieldBaseService implements FieldServiceService {

    @Resource
    private FieldServiceItemDao fieldServiceItemDao;

    @Resource
    private FieldServiceWorkOrderDao fieldServiceWorkOrderDao;

    @Resource
    private FieldServiceInvestigationDao fieldServiceInvestigationDao;

    @Resource
    private FieldServiceTemplateDao fieldServiceTemplateDao;

    @Resource
    private FieldServiceTemplateSectionDao fieldServiceTemplateSectionDao;

    @Resource
    private FieldServiceTemplateParamDao fieldServiceTemplateParamDao;

    @Resource
    private FieldServiceReportResultDao fieldServiceReportResultDao;

    @Resource
    private SyncProcessor syncProcessor;

    @Resource
    private FieldServiceEngineerDao fieldServiceEngineerDao;

    @Resource
    private DictionariesTService dictionariesTService;

    @Resource
    private FieldServiceInvestigationReportDao fieldServiceInvestigationReportDao;

    @Resource
    private FieldServiceAgreementDao fieldServiceAgreementDao;

    @Resource
    private FieldServiceUpgradeDao fieldServiceUpgradeDao;

    @Resource
    private FieldServiceTemplateStandardDao fieldServiceTemplateStandardDao;

    @Resource
    private FieldServiceTemplatePickParamDao fieldServiceTemplatePickParamDao;

    @Resource
    private FieldServiceWorkOrderFlowService fieldServiceWorkOrderFlowService;

    @Resource
    private FieldServiceReportService fieldServiceReportService;

    @Override
    public void getOpenItemList(PagedRequest pagedRequest) {
        PageHelper.startPage(pagedRequest.getPage(), pagedRequest.getPageSize());
        Long channel = ChannelThreadLocal.get();
        // 通过渠道+当前时间，获取任务大厅列表，并分页
        List<FieldServiceItem> openItemList = fieldServiceItemDao.getOpenItemList(channel, LocalTimeUtil.getRealCurrentTime());
        PageInfo<FieldServiceItem> info = new PageInfo<>(openItemList);
        PagedResponse<GetItemResponse> response = new PagedResponse<>();
        response.setTotal(info.getTotal());
        List<GetItemResponse> responseList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(info.getList())) {
            for (FieldServiceItem item : info.getList()) {
                // 拼装ITEM响应数据
                GetItemResponse itemResponse = converterItem(channel, item);
                responseList.add(itemResponse);
            }
        }
        response.setList(responseList);
        ParameterTool.writeSuccessResponse(RequestContextHolder.getResponse(), response);
    }

    @Override
    public void getItem(Long itemId) {
        HttpServletResponse response = RequestContextHolder.getResponse();
        Long channel = ChannelThreadLocal.get();
        FieldServiceItem item = fieldServiceItemDao.selectByPrimaryKey(itemId);
        if (null != item) {
            // 拼装ITEM响应数据
            GetItemResponse itemResponse = converterItem(channel, item);
            ParameterTool.writeSuccessResponse(response, itemResponse);
        } else {
            ParameterTool.writeResponse(response, 1, "服务信息不存在");
        }
    }

    @Override
    public void startItemService(StartItemServiceRequest startItemServiceRequest) {
        HttpServletResponse response = RequestContextHolder.getResponse();
        UserT userT = UserThreadLocal.get();
        FieldServiceItem item = fieldServiceItemDao.selectByPrimaryKey(startItemServiceRequest.getItemId());
        if (null != item) {
            FieldServiceWorkOrder workOrder = BeanUtils.convert(startItemServiceRequest,FieldServiceWorkOrder.class);
            workOrder.setChannel(item.getChannel());
            workOrder.setWorkOrderNo(getOrderNo());
            workOrder.setEngineerId(userT.getId());
            workOrder.setEngineerWWID(userT.getEmployeeNum());
            workOrder.setRequestStartDate(LocalTimeUtil.getRealCurrentTime());
            // 基于时间，将item截止日置为WO截止日
            if (item.getCompleteType().equals("1")) {
                workOrder.setRequestEndDate(item.getEndTime());
            }
            // 将WO置为处理中状态
            workOrder.setStatus(FieldServiceWorkOrderStatus.IN_PROCESS.getCode());
            workOrder.setCreator(userT.getId());
            workOrder.setCreatorName(userT.getContact());
            workOrder.setCreateTime(LocalTimeUtil.getRealCurrentTime());
            fieldServiceWorkOrderDao.insertSelective(workOrder);
            // 更新Item
            completeItem(workOrder, userT);
            // TODO: 2020/1/9 同步crm
            syncProcessor.syncInfoToCrm(item.getId(), SyncInterface.SYNC_WORK, workOrder);
            StartItemServiceResponse responseData = BeanUtils.convert(workOrder, StartItemServiceResponse.class);
            // 保存工单流水记录
            fieldServiceWorkOrderFlowService.saveWorkOrderFlow(WorkOrderFlowProcessorType.USER, workOrder, userT.getId(), "用户领取悬赏任务");
            ParameterTool.writeSuccessResponse(response, responseData);
        } else {
            ParameterTool.writeResponse(response, 2, "未知服务信息");
        }
    }

    @Override
    public void getItemList(PagedRequest pagedRequest) {
        HttpServletResponse response = RequestContextHolder.getResponse();
        UserT userT = UserThreadLocal.get();
        Long channel = ChannelThreadLocal.get();
        PageHelper.startPage(pagedRequest.getPage(), pagedRequest.getPageSize());
        // 查询当前工程师领取的悬赏任务工单
        List<FieldServiceWorkOrder> workOrderList = fieldServiceWorkOrderDao.selectOpenListByEngineerId(channel, userT.getId());
        PageInfo<FieldServiceWorkOrder> info = new PageInfo<>(workOrderList);
        PagedResponse<GetOrderResponse> orderResponsePagedResponse = new PagedResponse<>();
        orderResponsePagedResponse.setTotal(info.getTotal());
        List<GetOrderResponse> responseList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(info.getList())) {
            for (FieldServiceWorkOrder fieldServiceWorkOrder : info.getList()) {
                GetOrderResponse orderResponse = new GetOrderResponse();
                // 拼装WO响应
                orderResponse.setWorkOrderInfo(converterWorkOrder(channel, fieldServiceWorkOrder));
                // 通过工单，查询对应的Item信息
                FieldServiceItem item = fieldServiceItemDao.selectByPrimaryKey(fieldServiceWorkOrder.getItemId());
                // 拼装ITEM响应
                orderResponse.setItemInfo(converterItem(channel, item));
                responseList.add(orderResponse);
            }
        }
        orderResponsePagedResponse.setList(responseList);
        ParameterTool.writeSuccessResponse(response, orderResponsePagedResponse);
    }

    private GetItemResponse converterItem(Long channel, FieldServiceItem item) {
        GetItemResponse response = BeanUtils.convert(item, GetItemResponse.class);
        // 映射字典项值
        response.setFaultTypeValue(getDictionaryValue(FieldServiceDictionaryType.FAULT_TYPE, channel, item.getFaultType()));
        response.setRequestedFunctionValue(getDictionaryValue(FieldServiceDictionaryType.FUNCTION, channel, item.getRequestedFunction()));
        response.setEntityValue(getDictionaryValue(FieldServiceDictionaryType.ENTITY, channel, item.getEntity()));
        response.setRequestSourceTypeValue(getDictionaryValue(FieldServiceDictionaryType.SOURCE_TYPE, channel, item.getRequestSourceType()));
        return response;
    }

    private GetWorkOrderResponse converterWorkOrder(Long channel, FieldServiceWorkOrder workOrder) {
        GetWorkOrderResponse response = BeanUtils.convert(workOrder, GetWorkOrderResponse.class);
        // 映射字典项值
        response.setStatusValue(getDictionaryValue(FieldServiceDictionaryType.ORDER_STATUS, channel, workOrder.getStatus()));
        return response;
    }

    @Override
    @Transactional
    public void createWorkOrder(CreateWorkOrderRequest createWorkOrderRequest) {
        HttpServletResponse response = RequestContextHolder.getResponse();
        Long channel = ChannelThreadLocal.get();
        UserT userT = UserThreadLocal.get();
        FieldServiceEngineer engineer = fieldServiceEngineerDao.selectEngineer(channel, userT.getEmployeeNum());
        // 插入item信息
        FieldServiceItem item = BeanUtils.convert(createWorkOrderRequest.getItemInfo(), FieldServiceItem.class);
        item.setChannel(channel);
        // 将工程师的entity转换为字段表汉字值
        String requestOrganization = getDictionaryValue(FieldServiceDictionaryType.ENTITY, channel, engineer.getEntity());
        item.setRequestorOrganization(requestOrganization);
        // 设置申请日期为今天
        item.setRequestDate(LocalTimeUtil.getRealCurrentTime());
        // 通过来源类型，获取到优先级数据并设置优先级
        item.setPriority(getDictionaryValue(FieldServiceDictionaryType.PRIORITY, channel, item.getRequestSourceType()));
        // type=3，app报单
        item.setType(3);
        // 拼装item编号
        item.setItemNo(getItemNo());
        // item状态为处理中
        item.setStatus(FieldServiceItemStatus.IN_PROCESS.getCode());
        item.setCreator(userT.getId());
        item.setCreateTime(LocalTimeUtil.getRealCurrentTime());
        fieldServiceItemDao.insertSelective(item);
        // 插入WO信息
        FieldServiceWorkOrder workOrder = BeanUtils.convert(createWorkOrderRequest.getWorkOrderInfo(), FieldServiceWorkOrder.class);
        workOrder.setChannel(channel);
        workOrder.setItemId(item.getId());
        workOrder.setCreatorName(userT.getContact());
        workOrder.setCreatorPhone(userT.getPhone());
        workOrder.setWorkOrderNo(getOrderNo());
        workOrder.setEngineerId(userT.getId());
        workOrder.setEngineerWWID(userT.getEmployeeNum());
        // wo状态为待处理
        workOrder.setStatus(FieldServiceWorkOrderStatus.NEW.getCode());
        workOrder.setCreator(userT.getId());
        workOrder.setCreateTime(LocalTimeUtil.getRealCurrentTime());
        fieldServiceWorkOrderDao.insertSelective(workOrder);
        // 发送crm通知，此处特殊处理为了保证顺序性
        syncProcessor.syncOrderCreateInfoToCrm(item.getId(), engineer, item, workOrder);
        // 保存工单流水记录
        fieldServiceWorkOrderFlowService.saveWorkOrderFlow(WorkOrderFlowProcessorType.USER, workOrder, userT.getId(), "用户自主创建工单");
        // 返回工单id给前端
        Map<String, Object> data = new HashMap<>(1);
        data.put("workOrderId", String.valueOf(workOrder.getId()));
        ParameterTool.writeSuccessResponse(response, data);
    }

    @Override
    public void startService(Long orderId) {
        HttpServletResponse response = RequestContextHolder.getResponse();
        UserT userT = UserThreadLocal.get();
        FieldServiceWorkOrder workOrder = fieldServiceWorkOrderDao.selectByPrimaryKey(orderId);
        if (null != workOrder) {
            // 将工单置为处理中，此处不通知CRM，是因为工单创建时已将处理中状态同步CRM，此状态变更只是APP本身状态变更
            workOrder.setStatus(FieldServiceWorkOrderStatus.IN_PROCESS.getCode());
            workOrder.setUpdator(userT.getId());
            workOrder.setUpdateTime(LocalTimeUtil.getRealCurrentTime());
            fieldServiceWorkOrderDao.updateByPrimaryKeySelective(workOrder);
            // 保存工单流水信息
            fieldServiceWorkOrderFlowService.saveWorkOrderFlow(WorkOrderFlowProcessorType.USER, workOrder, userT.getId(), "用户开始服务");
            ParameterTool.writeSuccessResponse(response);
        } else {
            ParameterTool.writeResponse(response, 1, "未知工单信息");
        }
    }


    @Override
    public void getWorkOrderList(PagedRequest pagedRequest) {
        UserT userT = UserThreadLocal.get();
        Long channel = ChannelThreadLocal.get();
        PageHelper.startPage(pagedRequest.getPage(), pagedRequest.getPageSize());
        // 通过当前工程师ID获取工单列表
        List<FieldServiceWorkOrder> workOrderList = fieldServiceWorkOrderDao.selectListByEngineerId(channel, userT.getId());
        PageInfo<FieldServiceWorkOrder> info = new PageInfo<>(workOrderList);
        PagedResponse<GetOrderResponse> response = new PagedResponse<>();
        response.setTotal(info.getTotal());
        List<GetOrderResponse> responseList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(info.getList())) {
            for (FieldServiceWorkOrder fieldServiceWorkOrder : info.getList()) {
                GetOrderResponse orderResponse = new GetOrderResponse();
                // 拼装WO响应信息
                orderResponse.setWorkOrderInfo(converterWorkOrder(channel, fieldServiceWorkOrder));
                // 获取工单对应的item信息
                FieldServiceItem item = fieldServiceItemDao.selectByPrimaryKey(fieldServiceWorkOrder.getItemId());
                // 拼装ITEM响应信息
                orderResponse.setItemInfo(converterItem(channel, item));
                responseList.add(orderResponse);
            }
        }
        response.setList(responseList);
        ParameterTool.writeSuccessResponse(RequestContextHolder.getResponse(), response);
    }

    @Override
    public void getOrder(Long orderId) {
        HttpServletResponse response = RequestContextHolder.getResponse();
        Long channel = ChannelThreadLocal.get();
        // 通过工单ID获取工单信息
        FieldServiceWorkOrder workOrder = fieldServiceWorkOrderDao.selectByPrimaryKey(orderId);
        if (null != workOrder) {
            GetOrderResponse orderResponse = new GetOrderResponse();
            // 拼装wo响应
            orderResponse.setWorkOrderInfo(converterWorkOrder(channel, workOrder));
            FieldServiceItem item = fieldServiceItemDao.selectByPrimaryKey(workOrder.getItemId());
            // 拼装item响应
            orderResponse.setItemInfo(converterItem(channel, item));
            // 获取调查列表，前端显示开始调查/继续调查的依据
            List<GetInvestigationResponse> investigationResponses = new ArrayList<>();
            List<FieldServiceInvestigation> fieldServiceInvestigationList = fieldServiceInvestigationDao.selectListByOrderId(workOrder.getId());
            if (CollectionUtils.isNotEmpty(fieldServiceInvestigationList)) {
                investigationResponses = BeanUtils.convertList(fieldServiceInvestigationList, GetInvestigationResponse.class);
            }
            orderResponse.setInvestigationList(investigationResponses);
            // 如果工单时待处理状态，查询是否有保证书数据
            if (FieldServiceWorkOrderStatus.NEW.getCode().equals(workOrder.getStatus())) {
                FieldServiceAgreement agreement = fieldServiceAgreementDao.selectByChannelAndCategory(channel, FieldServiceAgreementCategory.START_SERVICE.getCode());
                if (null != agreement) {
                    // 有保证书，将保证书数据放入响应
                    orderResponse.setAgreement(BeanUtils.convert(agreement, GetAgreementResponse.class));
                }
            }
            ParameterTool.writeSuccessResponse(response, orderResponse);
        } else {
            ParameterTool.writeResponse(response, 1, "工单信息不存在");
        }
    }

    @Override
    public void getOrderDetail(Long orderId) {
        HttpServletResponse response = RequestContextHolder.getResponse();
        GetOrderDetailResponse orderDetailResponse = new GetOrderDetailResponse();
        FieldServiceWorkOrder workOrder = fieldServiceWorkOrderDao.selectByPrimaryKey(orderId);
        if (null != workOrder) {
            List<FieldServiceInvestigation> investigationList = fieldServiceInvestigationDao.selectListByOrderId(orderId);
            List<GetOrderDetailResponse.GetInvestigationResponse> investigationResponseList = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(investigationList)) {
                for (FieldServiceInvestigation investigation : investigationList) {
                    List<FieldServiceInvestigationReport> reportList = fieldServiceInvestigationReportDao.selectReportList(investigation.getId());
                    if (CollectionUtils.isNotEmpty(reportList)) {
                        GetOrderDetailResponse.GetInvestigationResponse investigationResponse = BeanUtils.convert(investigation, GetOrderDetailResponse.GetInvestigationResponse.class);
                        List<GetOrderDetailResponse.GetReportResultResponse> reportResultResponseList = new ArrayList<>();
                        for (FieldServiceInvestigationReport report : reportList) {
                            GetOrderDetailResponse.GetReportResultResponse reportResultResponse = BeanUtils.convert(report, GetOrderDetailResponse.GetReportResultResponse.class);
                            List<ReportResult> reportResultList = fieldServiceReportService.getReportResultList(report);
                            if (CollectionUtils.isNotEmpty(reportResultList)) {
                                List<GetOrderDetailResponse.GetParamResultResponse> paramResultResponseList = BeanUtils.convertList(reportResultList, GetOrderDetailResponse.GetParamResultResponse.class);
                                reportResultResponse.setParamResultList(paramResultResponseList);
                            }
                            if (CollectionUtils.isNotEmpty(reportResultResponse.getParamResultList())) {
                                reportResultResponseList.add(reportResultResponse);
                            }
                        }
                        if (CollectionUtils.isNotEmpty(reportResultResponseList)) {
                            investigationResponse.setReportList(reportResultResponseList);
                        }
                        investigationResponseList.add(investigationResponse);
                    }
                }
            }
            orderDetailResponse.setInvestigationList(investigationResponseList);
            ParameterTool.writeSuccessResponse(response, orderDetailResponse);
        }
    }

    @Override
    public void getInvestigationList(Long orderId) {
        HttpServletResponse response = RequestContextHolder.getResponse();
        // 通过工单id获取调查列表
        List<FieldServiceInvestigation> list = fieldServiceInvestigationDao.selectListByOrderId(orderId);
        GetInvestigationListResponse listResponse = new GetInvestigationListResponse();
        if (CollectionUtils.isNotEmpty(list)) {
            listResponse.setList(BeanUtils.convertList(list, GetInvestigationResponse.class));
        }
        ParameterTool.writeSuccessResponse(response, listResponse);
    }

    @Override
    public void createInvestigation(CreateInvestigationRequest request) {
        HttpServletResponse response = RequestContextHolder.getResponse();
        UserT userT = UserThreadLocal.get();
        // 创建调查，将调查名称放入数据库
        FieldServiceInvestigation investigation = BeanUtils.convert(request, FieldServiceInvestigation.class);
        investigation.setInvestigationNo(getInvestigationNo());
        investigation.setCreator(userT.getId());
        investigation.setCreateTime(LocalTimeUtil.getRealCurrentTime());
        fieldServiceInvestigationDao.insertSelective(investigation);
        CreateInvestigationResponse data = BeanUtils.convert(investigation, CreateInvestigationResponse.class);
        ParameterTool.writeSuccessResponse(response, data);
    }

    @Override
    public void deleteInvestigation(DeleteInvestigationRequest request) {
        HttpServletResponse response = RequestContextHolder.getResponse();
        UserT userT = UserThreadLocal.get();
        Long investigationId = request.getId();
        FieldServiceInvestigation investigation = fieldServiceInvestigationDao.selectByPrimaryKey(investigationId);
        if (null != investigation) {
            investigation.setFlag(-1);
            investigation.setDeleter(userT.getId());
            investigation.setDeleteTime(LocalTimeUtil.getRealCurrentTime());
            fieldServiceInvestigationDao.updateByPrimaryKeySelective(investigation);
        }
        ParameterTool.writeSuccessResponse(response);
    }

    @Override
    public void getReportList(Long orderId, Long investigationId) {
        HttpServletResponse response = RequestContextHolder.getResponse();
        GetReportListResponse listResponse = new GetReportListResponse();
        // 获取调查下的所有报告
        List<FieldServiceInvestigationReport> reportList = fieldServiceInvestigationReportDao.selectReportList(investigationId);
        listResponse.setList(BeanUtils.convertList(reportList, GetReportResponse.class));
        ParameterTool.writeSuccessResponse(response, listResponse);
    }

    @Override
    public void updateReport(UpdateReportRequest reportRequest) {
        HttpServletResponse response = RequestContextHolder.getResponse();
        UserT userT = UserThreadLocal.get();
        // 修改报告信息，当前业务为修改报告名称
        FieldServiceInvestigationReport report = BeanUtils.convert(reportRequest, FieldServiceInvestigationReport.class);
        report.setUpdator(userT.getId());
        report.setUpdateTime(LocalTimeUtil.getRealCurrentTime());
        fieldServiceInvestigationReportDao.updateByPrimaryKeySelective(report);
        ParameterTool.writeSuccessResponse(response);
    }

    @Override
    public void deleteReport(DeleteReportRequest deleteRequest) {
        HttpServletResponse response = RequestContextHolder.getResponse();
        UserT userT = UserThreadLocal.get();
        Long reportId = deleteRequest.getId();
        FieldServiceInvestigationReport report = fieldServiceInvestigationReportDao.selectByPrimaryKey(reportId);
        if (null != report) {
            report.setFlag(-1);
            report.setDeleter(userT.getId());
            report.setDeleteTime(LocalTimeUtil.getRealCurrentTime());
            fieldServiceInvestigationReportDao.updateByPrimaryKeySelective(report);
        }
        ParameterTool.writeSuccessResponse(response);
    }

    @Override
    public void getAvailableTemplateList(Long orderId, Long investigationId) {
        HttpServletResponse response = RequestContextHolder.getResponse();
        GetTemplateListResponse listResponse = new GetTemplateListResponse();
        Long channel = ChannelThreadLocal.get();
        // 获取所有可用模板列表
        List<FieldServiceTemplate> templateList = fieldServiceTemplateDao.getActiveTemplateList(channel);
        List<GetTemplateResponse> templateResponses = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(templateList)) {
            // 获取已经填写的报告列表
            List<FieldServiceInvestigationReport> reportList = fieldServiceInvestigationReportDao.selectReportList(investigationId);
            addList:
            for (FieldServiceTemplate template : templateList) {
                // 如果是基本模板或是CDS模板，如果存在已经填写的报告，则过滤
                if (FieldServiceTemplateType.BASIC.getCode().equals(template.getType())
                        || FieldServiceTemplateType.CDS.getCode().equals(template.getType())) {
                    if (CollectionUtils.isNotEmpty(reportList)) {
                        for (FieldServiceInvestigationReport report : reportList) {
                            if (report.getTemplateId().equals(template.getId())) {
                                continue addList;
                            }
                        }
                    }
                }
                // 将过滤以后的模板列表放入响应中
                GetTemplateResponse templateResponse = BeanUtils.convert(template, GetTemplateResponse.class);
                templateResponses.add(templateResponse);
            }
        }
        listResponse.setList(templateResponses);
        ParameterTool.writeSuccessResponse(response, listResponse);
    }

    @Override
    public void selectTemplate(SelectTemplateRequest request) {
        HttpServletResponse response = RequestContextHolder.getResponse();
        UserT userT = UserThreadLocal.get();
        FieldServiceInvestigationReport report = BeanUtils.convert(request, FieldServiceInvestigationReport.class);
        FieldServiceTemplate template = fieldServiceTemplateDao.selectByPrimaryKey(report.getTemplateId());
        if (null != template) {
            // 将调查+模板id关联生成报告数据，存入数据库
            report.setReportTitle(template.getTitle());
            report.setTemplateType(template.getType());
            report.setCreator(userT.getId());
            report.setCreateTime(LocalTimeUtil.getRealCurrentTime());
            fieldServiceInvestigationReportDao.insertSelective(report);
            GetReportResponse reportResponse = BeanUtils.convert(report, GetReportResponse.class);
            ParameterTool.writeSuccessResponse(response, reportResponse);
        } else {
            ParameterTool.writeResponse(response, 1, "模板信息不存在");
        }
    }

    @Override
    public void getTemplateSection(Long reportId, Long sectionId) {
        HttpServletResponse response = RequestContextHolder.getResponse();
        FieldServiceWorkOrder workOrder = fieldServiceWorkOrderDao.selectByReportId(reportId);
        if (null == workOrder) {
            ParameterTool.writeResponse(response, 1, "报告信息不存在");
            return;
        }
        FieldServiceInvestigationReport report = fieldServiceInvestigationReportDao.selectByPrimaryKey(reportId);
        // 没有片段ID，选择第一个section
        if (!NumberUtils.isPositiveNum(sectionId)) {
            FieldServiceTemplateSection currentSection = fieldServiceTemplateSectionDao.selectFirstByTemplateId(report.getTemplateId());
            if (null != currentSection) {
                GetTemplateSectionResponse sectionResponse = BeanUtils.convert(currentSection, GetTemplateSectionResponse.class);
                // 获取参数列表
                List<FieldServiceTemplateParam> paramList = getParamList(workOrder.getChannel(), reportId, currentSection.getId());
                sectionResponse.setParamList(BeanUtils.convertList(paramList, GetTemplateParamResponse.class));
                // 获取下一个sectionId
                sectionResponse.setNextId(getNextSectionIdStr(report.getTemplateId(), currentSection.getId()));
                ParameterTool.writeSuccessResponse(response, sectionResponse);
            } else {
                ParameterTool.writeResponse(response, 1, "模板Section不存在");
            }
        } else {
            FieldServiceTemplateSection currentSection = fieldServiceTemplateSectionDao.selectByPrimaryKey(sectionId);
            if (null != currentSection) {
                GetTemplateSectionResponse sectionResponse = BeanUtils.convert(currentSection, GetTemplateSectionResponse.class);
                List<FieldServiceTemplateParam> paramList = getParamList(workOrder.getChannel(), reportId, sectionId);
                sectionResponse.setParamList(BeanUtils.convertList(paramList, GetTemplateParamResponse.class));
                // 获取上一个sectionId
                sectionResponse.setPreviousId(getPreviousSectionIdStr(report.getTemplateId(), currentSection.getId()));
                // 获取下一个sectionId
                sectionResponse.setNextId(getNextSectionIdStr(report.getTemplateId(), currentSection.getId()));
                ParameterTool.writeSuccessResponse(response, sectionResponse);
            } else {
                ParameterTool.writeResponse(response, 1, "模板Section不存在");
            }
        }
    }

    private List<FieldServiceTemplateParam> getParamList(Long channel, Long reportId, Long sectionId) {
        // 获取模板参数列表
        List<FieldServiceTemplateParam> paramList = fieldServiceTemplateParamDao.selectListBySectionId(sectionId);
        if (CollectionUtils.isNotEmpty(paramList)) {
            for (FieldServiceTemplateParam param : paramList) {
                // 标准值
                if (StringUtils.isNotEmpty(param.getStandardKey())) {
                    FieldServiceTemplateStandard serviceTemplateStandard = fieldServiceTemplateStandardDao.select(channel, param.getStandardKey());
                    if (null != serviceTemplateStandard) {
                        param.setStandard(serviceTemplateStandard);
                    }
                }
                // PickList参数
                if (StringUtils.isNotEmpty(param.getPickList())) {
                    List<FieldServiceTemplatePickParam> pickParamList = fieldServiceTemplatePickParamDao.selectListByParamId(param.getId());
                    if (CollectionUtils.isNotEmpty(pickParamList)) {
                        param.setParamValueList(pickParamList);
                    }
                }
            }
            // 获取已经填写的内容
            FieldServiceReportResult queryResult = new FieldServiceReportResult();
            queryResult.setReportId(reportId);
            queryResult.setSectionId(sectionId);
            FieldServiceReportResult investigationResult = fieldServiceReportResultDao.selectByRecord(queryResult);
            if (null != investigationResult) {
                // 将填写内容补充至列表
                mergeParamResult(paramList, investigationResult);
            }
        }
        return paramList;
    }

    private String getPreviousSectionIdStr(Long templateId, Long sectionId) {
        FieldServiceTemplateSection previousSection = fieldServiceTemplateSectionDao.selectPreviousSection(templateId, sectionId);
        if (null != previousSection) {
            return String.valueOf(previousSection.getId());
        }
        return null;
    }

    private String getNextSectionIdStr(Long templateId, Long sectionId) {
        FieldServiceTemplateSection nextSection = fieldServiceTemplateSectionDao.selectNextSection(templateId, sectionId);
        if (null != nextSection) {
            return String.valueOf(nextSection.getId());
        }
        return null;
    }

    private void mergeParamResult(List<FieldServiceTemplateParam> paramList, FieldServiceReportResult investigationResult) {
        // 将填写的结果数组字符串，映射成结果列表
        String dataJson = investigationResult.getData();
        List<ReportResult> resultList = JsonUtils.convertJsonArrayToList(dataJson, ReportResult.class);
        if (CollectionUtils.isNotEmpty(resultList)) {
            Map<String, String> resultMap = new HashMap<>(resultList.size());
            Map<String, List<String>> extraMap = new HashMap<>(resultList.size());
            // 将列表中的值，以参数key为标志，放入结果Map+附件Map中
            for (ReportResult result : resultList) {
                resultMap.put(result.getKey(), result.getValue());
                if (CollectionUtils.isNotEmpty(result.getExtraData())) {
                    extraMap.put(result.getKey(), result.getExtraData());
                }
            }
            // 遍历要加入的参数列表，将结果和附件添加进去
            for (FieldServiceTemplateParam param : paramList) {
                String value = resultMap.get(param.getParamKey());
                if (null != value) {
                    param.setParamValue(value);
                }
                List<String> extraData = extraMap.get(param.getParamKey());
                if (CollectionUtils.isNotEmpty(extraData)) {
                    param.setExtraData(extraData);
                }
            }
        }
    }

    @Override
    public void submitTemplateSection(EditTemplateSectionRequest request) {
        HttpServletResponse response = RequestContextHolder.getResponse();
        UserT userT = UserThreadLocal.get();
        FieldServiceInvestigationReport report = fieldServiceInvestigationReportDao.selectByPrimaryKey(Long.valueOf(request.getReportId()));
        if (null == report) {
            ParameterTool.writeResponse(response, 1, "无效报告");
            return;
        }
        // 保存结果数据
        saveSectionResult(userT, request);
        // 如果当前报告已经填写完整，需要判断此次操作是否影响了完整性
        if (BooleanType.TRUE.getCode().equals(report.getIsComplete())) {
            // 如果获取未填写的必填字段
            FieldServiceTemplateParam requiredParam = getRequiredParam(report);
            // 未填写的必填字段不为空，则将报告状态置为不完整
            if (null != requiredParam) {
                report.setIsComplete(BooleanType.FALSE.getCode());
                report.setUpdator(userT.getId());
                report.setUpdateTime(LocalTimeUtil.getRealCurrentTime());
                fieldServiceInvestigationReportDao.updateByPrimaryKeySelective(report);
            }
        }
        ParameterTool.writeSuccessResponse(response);
    }

    @Override
    @Transactional
    public void finishTemplateSection(EditTemplateSectionRequest request) {
        HttpServletResponse response = RequestContextHolder.getResponse();
        UserT userT = UserThreadLocal.get();
        FieldServiceInvestigationReport report = fieldServiceInvestigationReportDao.selectByPrimaryKey(Long.valueOf(request.getReportId()));
        if (null == report) {
            ParameterTool.writeResponse(response, 1, "无效报告");
            return;
        }
        // 将内容存放至数据库
        saveSectionResult(userT, request);
        //判断该模板是否已完成填写
        FieldServiceTemplateParam requiredParam = getRequiredParam(report);
        if (null != requiredParam) {
            // 必填字段不为空，则提示用户填写必填字段
            ParameterTool.writeResponse(response, 1, "请填写必填字段：" + requiredParam.getParamName());
        } else {
            // 必填字段为空，说明均已填写，此时将报告完整字段置为1
            report.setIsComplete(BooleanType.TRUE.getCode());
            report.setUpdator(userT.getId());
            report.setUpdateTime(LocalTimeUtil.getRealCurrentTime());
            fieldServiceInvestigationReportDao.updateByPrimaryKeySelective(report);
            ParameterTool.writeSuccessResponse(response);
        }
    }

    private void saveSectionResult(UserT userT, EditTemplateSectionRequest request) {
        // 将内容存放至数据库
        FieldServiceReportResult queryResult = BeanUtils.convert(request, FieldServiceReportResult.class);
        FieldServiceReportResult reportResult = fieldServiceReportResultDao.selectByRecord(queryResult);
        List<ReportResultRequest> reportResultRequestList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(request.getData())) {
            for (ReportResultRequest resultRequest : request.getData()) {
                if (StringUtils.isNotEmpty(resultRequest.getValue()) || CollectionUtils.isNotEmpty(resultRequest.getExtraData())) {
                    reportResultRequestList.add(resultRequest);
                }
            }
        }
        // 该片段未填写结果，直接入库
        if (null != reportResult) {
            reportResult.setData(JsonUtils.toNonNullJsonString(reportResultRequestList));
            reportResult.setUpdator(userT.getId());
            reportResult.setUpdateTime(LocalTimeUtil.getRealCurrentTime());
            fieldServiceReportResultDao.updateByPrimaryKeySelective(reportResult);
        } else {
            // 该片段填写结果，直接覆盖
            queryResult.setData(JsonUtils.toJsonString(reportResultRequestList));
            queryResult.setCreator(userT.getId());
            queryResult.setCreateTime(LocalTimeUtil.getRealCurrentTime());
            fieldServiceReportResultDao.insertSelective(queryResult);
        }
    }

    private FieldServiceTemplateParam getRequiredParam(FieldServiceInvestigationReport report) {
        if (null != report) {
            // 查询该报告所有填写
            List<FieldServiceReportResult> reportResultList = fieldServiceReportResultDao.selectByReportId(report.getId());
            // 获取所有已经填写的Key
            List<String> resultParamList = getResultKeyList(reportResultList);
            // 通过报告中模板ID查询所有必填参数
            List<FieldServiceTemplateParam> requiredParamList = fieldServiceTemplateParamDao.selectRequiredParamListByTemplateId(report.getTemplateId());
            // 如果必填参数不为空
            if (CollectionUtils.isNotEmpty(requiredParamList)) {
                // 遍历必填参数列表
                for (FieldServiceTemplateParam requiredParam : requiredParamList) {
                    // 已填写的参数Key不在必填参数里边，返回该必填参数信息
                    if (!resultParamList.contains(requiredParam.getParamKey())) {
                        return requiredParam;
                    }
                }
            }
            return null;
        } else {
            return null;
        }

    }

    private List<String> getResultKeyList(List<FieldServiceReportResult> fieldServiceReportResultList) {
        // 已经填写的字段Key值列表
        List<String> resultKeyList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(fieldServiceReportResultList)) {
            for (FieldServiceReportResult fieldServiceReportResult : fieldServiceReportResultList) {
                String data = fieldServiceReportResult.getData();
                if (StringUtils.isNotEmpty(data)) {
                    // 将填充的结果JSON映射成结果对象列表
                    List<ReportResult> reportResultList = JsonUtils.convertJsonArrayToList(data, ReportResult.class);
                    if (CollectionUtils.isNotEmpty(reportResultList)) {
                        for (ReportResult reportResult : reportResultList) {
                            // 若该值对应的value已经填写，则该key已经填写
                            if (StringUtils.isNotEmpty(reportResult.getValue())) {
                                // 将已经填写的key值放入结果列表
                                resultKeyList.add(reportResult.getKey());
                            }
                        }
                    }
                }
            }
        }
        return resultKeyList;
    }

    @Override
    public void getDictionary(String type, String keyword) {
        HttpServletResponse response = RequestContextHolder.getResponse();
        Long channel = ChannelThreadLocal.get();
        if (StringUtils.isEmpty(type)) {
            ParameterTool.writeResponse(response, 1, "字典项类型不能为空");
            return;
        }
        // 通过type+remark获取字典项列表
        List<Map<String, Object>> dictionaries = dictionariesTService.getDictionaryRemark(type, String.valueOf(channel));
        List<Map<String, Object>> resultList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(dictionaries)) {
            for (Map<String, Object> dictionary : dictionaries) {
                Map<String, Object> result = new HashMap<>(2);
                String value = MapUtils.getString(dictionary, "DValue");
                // 当过滤参数不为空时，进行过滤
                if (StringUtils.isNotEmpty(keyword)) {
                    if (value.toUpperCase().contains(keyword.toUpperCase())) {
                        result.put("key", MapUtils.getInteger(dictionary, "DInt"));
                        result.put("name", MapUtils.getString(dictionary, "DValue"));
                        resultList.add(result);
                    }
                } else {
                    result.put("key", MapUtils.getInteger(dictionary, "DInt"));
                    result.put("name", MapUtils.getString(dictionary, "DValue"));
                    resultList.add(result);
                }
            }
        }
        ParameterTool.writeSuccessResponse(response, resultList);
    }

    @Override
    @Transactional
    public void workOrderUpgrade(WorkOrderUpgradeRequest request) {
        HttpServletResponse response = RequestContextHolder.getResponse();
        if (NumberUtils.isNumber(request.getOrderId())) {
            UserT userT = UserThreadLocal.get();
            FieldServiceWorkOrder workOrder = fieldServiceWorkOrderDao.selectByPrimaryKey(Long.valueOf(request.getOrderId()));
            if (null != workOrder && workOrder.getEngineerId().equals(userT.getId())) {
                // 取消升级
                if ("0".equals(request.getType())) {
                    FieldServiceUpgrade dataUpgrade = fieldServiceUpgradeDao.selectLastByOrderId(workOrder.getId());
                    // 存在未完成升级，不允许升级
                    if (null != dataUpgrade && !dataUpgrade.getStatus().equals(FieldServiceUpgradeStatus.CANCEL.getCode())) {
                        // 更新工单状态
                        workOrder.setStatus(FieldServiceWorkOrderStatus.IN_PROCESS.getCode());
                        workOrder.setUpdator(userT.getId());
                        workOrder.setUpdateTime(LocalTimeUtil.getRealCurrentTime());
                        fieldServiceWorkOrderDao.updateByPrimaryKey(workOrder);
                        // 更新升级状态
                        dataUpgrade.setStatus(FieldServiceUpgradeStatus.CANCEL.getCode());
                        dataUpgrade.setSolution(request.getMessage());
                        dataUpgrade.setUpdator(userT.getId());
                        dataUpgrade.setUpdateTime(LocalTimeUtil.getRealCurrentTime());
                        fieldServiceUpgradeDao.updateByPrimaryKeySelective(dataUpgrade);
                        // 将取消升级的通知，通知crm
                        syncProcessor.syncInfoToCrm(workOrder.getItemId(), SyncInterface.SYNC_UPGRADE, dataUpgrade);
                        // 保存工单流水记录
                        fieldServiceWorkOrderFlowService.saveWorkOrderFlow(WorkOrderFlowProcessorType.USER, workOrder, userT.getId(), "用户取消升级");
                        ParameterTool.writeSuccessResponse(response);
                    } else {
                        ParameterTool.writeResponse(response, 2, "非法操作");
                    }
                } else {
                    FieldServiceItem item = fieldServiceItemDao.selectByPrimaryKey(workOrder.getItemId());
                    // 如果是悬赏任务
                    if (FieldServiceItemType.OPEN.getCode().equals(item.getType())) {
                        if (FieldServiceUpgradeType.REQUEST_CANCEL.getCode().toString().equals(request.getType())) {
                            long durationMinutes = LocalTimeUtil.getDurationMinutes(workOrder.getCreateTime(), LocalTimeUtil.getRealCurrentTime());
                            if (durationMinutes <= 120L) {
                                FieldServiceUpgrade upgrade = BeanUtils.convert(request, FieldServiceUpgrade.class);
                                upgrade.setRequest(request.getMessage());
                                // 将工单状态置为已取消
                                workOrder.setStatus(FieldServiceWorkOrderStatus.CANCELLED.getCode());
                                workOrder.setUpdator(userT.getId());
                                workOrder.setUpdateTime(LocalTimeUtil.getRealCurrentTime());
                                fieldServiceWorkOrderDao.updateByPrimaryKeySelective(workOrder);
                                // 将item完成次数减1
                                item.setCompleteCount(item.getCompleteCount() - 1);
                                item.setUpdator(userT.getId());
                                item.setUpdateTime(LocalTimeUtil.getRealCurrentTime());
                                fieldServiceItemDao.updateByPrimaryKeySelective(item);
                                // 设置升级状态为已完成
                                upgrade.setStatus(FieldServiceUpgradeStatus.FINISH.getCode());
                                upgrade.setCreator(userT.getId());
                                upgrade.setCreateTime(LocalTimeUtil.getRealCurrentTime());
                                // 插入升级信息表
                                fieldServiceUpgradeDao.insertSelective(upgrade);
                                // 升级信息通知CRM
                                syncProcessor.syncInfoToCrm(workOrder.getItemId(), SyncInterface.SYNC_STATUS, workOrder, request.getMessage());
                                // 保存工单流水记录
                                fieldServiceWorkOrderFlowService.saveWorkOrderFlow(WorkOrderFlowProcessorType.USER, workOrder, userT.getId(), "用户工单升级,升级类型：" + request.getType());
                            } else {
                                doUpgrade(request, workOrder, userT);
                            }
                            ParameterTool.writeSuccessResponse(response);
                        } else {
                            // 工单信息为空或非本人工单时，非法操作
                            ParameterTool.writeResponse(response, 2, "非法操作");
                        }
                    } else {
                        // 升级操作
                        doUpgrade(request, workOrder, userT);
                        ParameterTool.writeSuccessResponse(response);
                    }
                }
            } else {
                // 工单信息为空或非本人工单时，非法操作
                ParameterTool.writeResponse(response, 2, "非法操作");
            }
        } else {
            ParameterTool.writeResponse(response, 1, "非法工单ID");
        }
    }

    private void doUpgrade(WorkOrderUpgradeRequest request, FieldServiceWorkOrder workOrder, UserT userT) {
        FieldServiceUpgrade upgrade = BeanUtils.convert(request, FieldServiceUpgrade.class);
        upgrade.setRequest(request.getMessage());
        // 请求延期，不需要审核，直接设置为完成
        if ("3".equals(request.getType())) {
            upgrade.setStatus(FieldServiceUpgradeStatus.FINISH.getCode());
        } else {
            // 更新工单状态
            workOrder.setStatus(FieldServiceWorkOrderStatus.ESCALATION.getCode());
            workOrder.setUpdator(userT.getId());
            workOrder.setUpdateTime(LocalTimeUtil.getRealCurrentTime());
            fieldServiceWorkOrderDao.updateByPrimaryKeySelective(workOrder);
            // 设置升级状态为处理中
            upgrade.setStatus(FieldServiceUpgradeStatus.ON_PROCESS.getCode());
        }
        upgrade.setCreator(userT.getId());
        upgrade.setCreateTime(LocalTimeUtil.getRealCurrentTime());
        // 插入升级信息表
        fieldServiceUpgradeDao.insertSelective(upgrade);
        // 升级信息通知CRM
        syncProcessor.syncInfoToCrm(workOrder.getItemId(), SyncInterface.SYNC_UPGRADE, upgrade);
        // 保存工单流水记录
        fieldServiceWorkOrderFlowService.saveWorkOrderFlow(WorkOrderFlowProcessorType.USER, workOrder, userT.getId(), "用户工单升级,升级类型：" + request.getType());

    }

    @Override
    public void getUpgradeList(Long orderId) {
        HttpServletResponse response = RequestContextHolder.getResponse();
        List<FieldServiceUpgrade> upgradeList = fieldServiceUpgradeDao.selectListByOrderId(orderId);
        GetUpgradeListResponse data = new GetUpgradeListResponse();
        List<GetUpgradeResponse> upgradeResponseList = BeanUtils.convertList(upgradeList, GetUpgradeResponse.class);
        data.setUpgradeList(upgradeResponseList);
        ParameterTool.writeSuccessResponse(response, data);
    }

    @Override
    public void workOrderCompletion(WorkOrderCompletionRequest request) {
        HttpServletResponse response = RequestContextHolder.getResponse();
        UserT userT = UserThreadLocal.get();
        FieldServiceWorkOrder workOrder = fieldServiceWorkOrderDao.selectByPrimaryKey(Long.valueOf(request.getOrderId()));
        if (null != workOrder) {
            // 获取工单的调查报告列表
            List<FieldServiceInvestigationReport> reportList = fieldServiceInvestigationReportDao.selectReportListByOrderId(workOrder.getId());
            if (CollectionUtils.isEmpty(reportList)) {
                ParameterTool.writeResponse(response, 2, "请进行相关报告填写，才能完工");
                return;
            } else {
                for (FieldServiceInvestigationReport report : reportList) {
                    // 包含未完成的报告
                    if (BooleanType.FALSE.getCode().equals(report.getIsComplete())) {
                        FieldServiceInvestigation investigation = fieldServiceInvestigationDao.selectByPrimaryKey(report.getInvestigationId());
                        ParameterTool.writeResponse(response, 3, "请完善" + investigation.getTitle() + "下" + report.getReportTitle() + "等相关报告内容，才能完工");
                        return;
                    }
                }
            }
            // 更新工单状态
            workOrder.setStatus(FieldServiceWorkOrderStatus.CLOSURE_INITIATED.getCode());
            workOrder.setUpdator(userT.getId());
            workOrder.setUpdateTime(LocalTimeUtil.getRealCurrentTime());
            fieldServiceWorkOrderDao.updateByPrimaryKeySelective(workOrder);
            // 同步工单状态至CRM系统
            syncProcessor.syncInfoToCrm(workOrder.getItemId(), SyncInterface.SYNC_STATUS, workOrder);
            // 保存工单流水记录
            fieldServiceWorkOrderFlowService.saveWorkOrderFlow(WorkOrderFlowProcessorType.USER, workOrder, userT.getId(), "用户完成工单");
            // 同步CRM报告信息
            fieldServiceReportService.syncReport(workOrder);
            // 响应前端
            ParameterTool.writeSuccessResponse(response);
        } else {
            ParameterTool.writeResponse(response, 1, "查无工单信息");
        }
    }

    private void completeItem(FieldServiceWorkOrder workOrder, UserT userT) {
        FieldServiceItem fieldServiceItem = fieldServiceItemDao.selectByPrimaryKey(workOrder.getItemId());
        // 完成次数+1
        Integer newCompleteCount = fieldServiceItem.getCompleteCount() + 1;
        // 如果基于次数的item，新完成次数大于等于设定完成次数，将item置为关闭
        fieldServiceItem.setCompleteCount(newCompleteCount);
        fieldServiceItem.setUpdator(userT.getId());
        fieldServiceItem.setUpdateTime(LocalTimeUtil.getRealCurrentTime());
        fieldServiceItemDao.updateByPrimaryKeySelective(fieldServiceItem);
    }

    /**
     * 通过字典项type，remark和key字段获取对应Value
     *
     * @param dictionaryType 字典项类型
     * @param channel        映射字典表remark字段
     * @param key            字典项key
     * @return DValue
     */
    private String getDictionaryValue(FieldServiceDictionaryType dictionaryType, Long channel, Integer key) {
        List<Map<String, Object>> dictionaries = dictionariesTService.getDictionaryRemark(dictionaryType.getCode(), String.valueOf(channel));
        if (CollectionUtils.isNotEmpty(dictionaries)) {
            for (Map<String, Object> map : dictionaries) {
                Integer dInt = MapUtils.getInteger(map, "DInt");
                if (dInt.equals(key)) {
                    return MapUtils.getString(map, "DValue");
                }
            }
        }
        return null;
    }

    /**
     * 通过字典项type，remark和字符串类型key字段获取对应Value
     *
     * @param dictionaryType 字典项类型
     * @param channel        映射字典表remark字段
     * @param key            字典项key
     * @return DValue
     */
    private String getDictionaryValue(FieldServiceDictionaryType dictionaryType, Long channel, String key) {
        return this.getDictionaryValue(dictionaryType, channel, Integer.valueOf(key));
    }
}
